<template>
  <div class="user-management">
    <AppNavbar title="用户管理" role="admin" />
    
    <!-- 搜索条件 -->
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
        </div>
      </template>
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable>
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="教师" :value="2"></el-option>
            <el-option label="学生" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUsers" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetSearch" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <div class="actions">
      <el-button type="primary" @click="openCreateDialog" icon="el-icon-plus">创建用户</el-button>
    </div>
    
    <!-- 用户列表表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <span class="record-count">共 {{ total }} 条记录</span>
        </div>
      </template>
      <el-table :data="userList" style="width: 100%" v-loading="loading">
        <el-table-column prop="username" label="用户名" width="200"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column label="角色" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.roleId === 1">管理员</el-tag>
            <el-tag v-else-if="scope.row.roleId === 2" type="success">教师</el-tag>
            <el-tag v-else-if="scope.row.roleId === 3" type="warning">学生</el-tag>
            <span v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editUser(scope.row)" icon="el-icon-edit">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row.id)" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    
    <!-- 创建/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userForm.roleId" placeholder="请选择角色">
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="教师" :value="2"></el-option>
            <el-option label="学生" :value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import AppNavbar from '@/components/AppNavbar.vue'
import AdminAPI from '@/api/admin'

export default {
  name: 'UserManagement',
  components: {
    AppNavbar
  },
  data() {
    return {
      searchForm: {
        username: '',
        roleId: null
      },
      userList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      isCreate: false, // true为创建，false为编辑
      userForm: {
        id: null,
        username: '',
        email: '',
        password: '',
        roleId: null
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.isCreate ? '创建用户' : '编辑用户'
    }
  },
  created() {
    this.fetchUserList()
  },
  methods: {
    // 获取用户列表
    async fetchUserList() {
      this.loading = true
      try {
        const res = await AdminAPI.getUserList(
          this.currentPage - 1, 
          this.pageSize, 
          this.searchForm.username, 
          this.searchForm.roleId
        )
        if (res.data.code === 200 && res.data.msg === 'success') {
          // 修复数据结构不匹配的问题
          this.userList = res.data.data.list || []
          this.total = res.data.data.total || 0
        } else {
          this.$message.error(res.data.message || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.loading = false
      }
    },

    // 搜索用户
    searchUsers() {
      this.currentPage = 1
      this.fetchUserList()
    },

    // 重置搜索条件
    resetSearch() {
      this.searchForm.username = ''
      this.searchForm.roleId = null
      this.currentPage = 1
      this.fetchUserList()
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.fetchUserList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUserList()
    },

    // 打开创建用户对话框
    openCreateDialog() {
      this.isCreate = true
      this.userForm = {
        id: null,
        username: '',
        email: '',
        password: '',
        roleId: null
      }
      this.dialogVisible = true
    },

    // 编辑用户
    editUser(user) {
      this.isCreate = false
      this.userForm = { ...user }
      // 清空密码字段，编辑时不需要填写密码
      this.userForm.password = ''
      this.dialogVisible = true
    },

    // 提交表单（创建或更新用户）
    handleSubmit() {
      this.$refs.userForm.validate(async (valid) => {
        if (valid) {
          try {
            let res
            if (this.isCreate) {
              // 创建用户
              res = await AdminAPI.createUser(this.userForm)
            } else {
              // 更新用户
              res = await AdminAPI.updateUser(this.userForm)
            }

            if (res.data.code === 200 && res.data.msg === 'success') {
              this.$message.success(this.isCreate ? '用户创建成功' : '用户更新成功')
              this.dialogVisible = false
              this.fetchUserList()
            } else {
              this.$message.error(res.data.message || (this.isCreate ? '用户创建失败' : '用户更新失败'))
            }
          } catch (error) {
            console.error(this.isCreate ? '创建用户失败:' : '更新用户失败:', error)
            this.$message.error((this.isCreate ? '用户创建失败: ' : '用户更新失败: ') + (error.response?.data?.message || error.message))
          }
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },

    // 删除用户
    deleteUser(userId) {
      this.$confirm('确定要删除这个用户吗？删除后将无法恢复！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await AdminAPI.deleteUser(userId)
          if (res.data.code === 200 && res.data.msg === 'success') {
            this.$message.success('用户删除成功')
            this.fetchUserList()
          } else {
            this.$message.error(res.data.message || '用户删除失败')
          }
        } catch (error) {
          console.error('删除用户失败:', error)
          this.$message.error('用户删除失败: ' + (error.response?.data?.message || error.message))
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  min-height: calc(100vh - 40px);
}

.search-card, .table-card {
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 30px;
  color: white;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
}

.record-count {
  font-size: 0.9rem;
  opacity: 0.8;
}

.actions {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
  background: rgba(255, 255, 255, 0.08);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: white;
}
</style>